//
//  HttpResponse.m
//  WaDaoServiceDemo
//
//  Created by wulanzhou on 16/6/3.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "HttpResponse.h"
#import "SystemUser.h"

@implementation HttpResponse


/**
 *  失败请求初始化
 *
 *  @param error
 *
 *  @return
 */
- (id)initWithError:(NSError *)error{
    self = [super init];
    if (self){
    
        self.code=@"-3";
        self.errMsg=error.description;
    }
    return self;
}

/**
 *  初始化
 *
 *  @param responseObject 请求返回的数据
 *
 *  @return
 */
- (id)initWithDictionary:(NSDictionary *)responseObject{

    self = [super init];
    if (self) {
        
        NSLog(@"responseObject =%@",responseObject);
        
        if (responseObject&&[responseObject isKindOfClass:[NSDictionary class]]&&[responseObject count]>0) {
        
            if ([responseObject.allKeys containsObject:@"code"]) {
                self.code=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]];
            }else{
                self.code=@"-1";
            }

            if ([responseObject.allKeys containsObject:@"msg"]) {
                self.errMsg=[responseObject objectForKey:@"msg"];
            }else{
                self.errMsg=@"未取到状态码";
            }
            
            //返回的数据
            if ([responseObject.allKeys containsObject:@"data"]){
            
                self.responseData=[responseObject objectForKey:@"data"];
            }
            
            
        }else{
            self.code=@"-2";
            self.errMsg=@"数据解析失败";
        }
        
    }
    return self;
}

#pragma mark -属性

- (void)setCode:(NSString *)responseCode{

    if (_code!=responseCode) {
        _code=responseCode;
        
        //登录已过期，需要重新登录,发出通知
        if (responseCode&&[responseCode isKindOfClass:[NSString class]]&&[responseCode length]>0&&[responseCode isEqualToString:@"007"]) {
            
            //删除登录信息
            [[SystemUser shareInstance] removeUser];
            
            NSLog(@"登录已过期，需要重新登录,发出通知");
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTokenExpiresReLogin object:nil];
        }
    }
}

- (BOOL)success{

    if (self.code&&[self.code length]>0&&[self.code isEqualToString:@"000"]) {
        return  YES;
    }
    return NO;
}

@end
